﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BSF.SystemConfig;
using HuntingFishGame.Domain.Model.WeChat;
using Newtonsoft.Json;

namespace HuntingFishGame.Domain.BLL.WeChat
{
    public class WeixinConfig
    {
        /*
         * ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
            【公司开发环境（从开发者模式扫描进入的测试号）】
            测试公众微信号： gh_1228689c8fb7

            ---测试号信息
            appID：wx0848e6965d142f2e
            appsecret：d4624c36b6795d1d99dcf0547af5443d

            ---消息接口配置信息
            URL：http://www.xxx.com/weixin/index
            Token：hbMqgmlWzawVI_6cj3bNwnw7ABUE7b3zd61BmNMiqmQ-zEHf2ZB8hIVNGhd-ZbZZpBtLk-Lt1IEO7oPaRvGZqAF5u_0H1rOHJnWUjsS2eqg

            ---JS接口安全域名
            http://192.168.0.60:8006

            -- 二维码图片
            http://mmbiz.qpic.cn/mmbiz/giaOP5RCZpzsFicjPoicbpC6sr62BOLf2JS0JJYIJP2h8ryptsealMN7xlZ7KmJV17DM7GicHElz688RlcRXjzCgjg/0
         */
        /// <summary>
        /// 公众号测试账号
        /// </summary>
        public class DevConfig
        {
            public const string AppIdCert = "wx0848e6965d142f2e";
            public const string AppSecretCert = "d4624c36b6795d1d99dcf0547af5443d";
            // 应用站点
            public const string AppId = "wx0848e6965d142f2e";
            public const string AppSecret = "d4624c36b6795d1d99dcf0547af5443d";
            public const string AppCallBackHost = "http://192.168.0.60:8006";
            //微信上传图片地址
            public const string AppWeixinPicHost = "http://hitongxue.oss-cn-hangzhou.aliyuncs.com/";

            //获取access_token https://mp.weixin.qq.com/debug/cgi-bin/apiinfo?t=index&type=%E5%9F%BA%E7%A1%80%E6%94%AF%E6%8C%81&form=%E8%8E%B7%E5%8F%96access_token%E6%8E%A5%E5%8F%A3%20/token
            public const string AccessToken = "GudvDM018sA5BtdXIiaQg9GHuoNkMJ-J2cK4EsxbWVFsJ4gAs03GzdZsbeGVlDuU3nkjfCw-JRc97gThBLYiqPNw3OBOqD34nqWl3qua74il8IETRx3GgZJIocShxvVaNJReAAAFBJ";
            //获取jsapiticket https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
            public const string JSApiTicket = "kgt8ON7yVITDhtdwci0qeTOttXQrMncmPjUYg5s5jF3up39XP31uqn22MHMMdCtmAvPHQZ6JGrH3k3WU8tkveA";
            public const string OpenId = "oyrtlv_b2tRIqF3C2Uvw7Iaw4TmU";
        }

        /// <summary>
        /// 是否调试模式（1测试，0正式）
        /// <para>根据此值判断处理相关配置返回数据</para>
        /// </summary>
        public static bool IsDebug
        {
            get
            {
                string val = GetAppSetting("IsDebug", "0");
                return "1".Equals(val) ? true : false;
            }
        }

        private static string GetAppSetting(string key, string defaultval = "", bool isselectdb = false, WeixinType certtype = WeixinType.CertServiceAccount)
        {
            string val = defaultval;
            //读取统一配置中心配置(优先读取本地配置文件)
            //val = Bronze.Core.BasicService.ConfigManager.ConfigManagerHelper.Get<string>(key);
            //读取配置文件
            string info = BSFConfig.Get(key);
            if (!string.IsNullOrWhiteSpace(info))
            {
                val = info;
            }  
            else
            {
                //如果配置文件没有，则查询微信配置库(存储公众号相关配置)
                if (isselectdb)
                {
                    //查询数据库
                    WeChatConfigModel item = WeChatConfigBLL.GetModelByParamKey(BSFConfig.MainConnectString, key.ToLower(), certtype);
                    if (item != null)
                        val = item.ParamValue;
                }
            }
            return val;
        }

        #region 微信应用配置
        /// <summary>
        /// 从配置中获取
        /// </summary>
        /// <param name="item"></param>
        public static void GetAppIdSecret(ref bool item)
        {
            List<WeChatSystemConfigModel> list = JsonConvert.DeserializeObject<List<WeChatSystemConfigModel>>(BSFConfig.WeChatConfig);
            item = list.Select(p => p.WeixinType == WeixinType.CertServiceAccount).FirstOrDefault();
        }

        /// <summary>
        /// 返回配置公众号appId
        /// <para>IsDebug:返回DevConfig.AppId</para>
        /// </summary>
        public static string AppId(WeixinType certtype)
        {
            if (IsDebug)
            {
                if (certtype.Equals(WeixinType.CertServiceAccount))
                    return DevConfig.AppIdCert;
                else
                    return DevConfig.AppId;
            }
            return GetAppSetting("AppId", "", true, certtype);
        }
        /// <summary>
        /// 返回配置公众号appSecret
        /// <para>IsDebug:返回DevConfig.AppSecret</para>
        /// </summary>
        public static string AppSecret(WeixinType certtype)
        {
            if (IsDebug)
            {
                if (certtype.Equals(WeixinType.CertServiceAccount))
                    return DevConfig.AppSecretCert;
                else
                    return DevConfig.AppSecret;
            }
            return GetAppSetting("AppSecret", "", true, certtype);
        }

        /// <summary>
        /// 返回配置公众号appId(授权认证服务号)
        /// <para>IsDebug:返回DevConfig.AppId</para>
        /// </summary>
        //public static string AppIdCert
        //{
        //    get
        //    {
        //        if (IsDebug)
        //        {
        //            return DevConfig.AppIdCert;
        //        }
        //        return GetAppSetting("AppIdCert");
        //    }
        //}
        /// <summary>
        /// 返回配置公众号appSecret(授权认证服务号)
        /// <para>IsDebug:返回DevConfig.AppSecret</para>
        /// </summary>
        //public static string AppSecretCert
        //{
        //    get
        //    {
        //        if (IsDebug)
        //        {
        //            return DevConfig.AppSecretCert;
        //        }
        //        return GetAppSetting("AppSecretCert");
        //    }
        //}

        public static string OpenId
        {
            get { return DevConfig.OpenId; }
        }

        /// <summary>
        /// 返回配置（AppCallBackHost）：        
        /// <para>IsDebug:返回DevConfig.AppCallBackHost</para>
        /// </summary>
        public static string SiteHost
        {
            get
            {
                if (IsDebug)
                {
                    return DevConfig.AppCallBackHost;
                }
                return GetAppSetting("AppCallBackHost");
            }
        }

        /// <summary>
        /// 微信上传图片域名
        /// </summary>
        public static string AppWeixinPicHost
        {
            get
            {
                if (IsDebug)
                {
                    return DevConfig.AppWeixinPicHost;
                }
                return GetAppSetting("AppWeixinPicHost");
            }
        }

        /// <summary>
        ///  临时使用的随机验证码（用户授权模式）
        /// </summary>
        public static string TmpRandomState_1
        {
            get
            {
                // TODO:需要处理为随机验证码
                return "sns01";
            }
        }

        /// <summary>
        ///  临时使用的随机验证码（静默授权模式）
        /// </summary>
        public static string TmpRandomState_2
        {
            get
            {
                // TODO:需要处理为随机验证码
                return "sns02";
            }
        }

        /// <summary>
        /// 获取access_token
        /// </summary>
        /// <param name="certtype">AppId,AppSecret类型</param>
        /// <returns></returns>
        public static WeChatConfigModel BaseAccessToken(WeixinType certtype)
        {
            if (IsDebug)
            {
                WeChatConfigModel item = new WeChatConfigModel()
                {
                    ParamKey = "access_token",
                    ParamValue = DevConfig.AccessToken,
                    ExpirationTime = DateTime.Now.AddDays(30)
                };
                return item;
            }
            else
            {
                string key = "access_token";
                WeChatConfigModel item = WeChatConfigBLL.GetModelByParamKey(BSFConfig.MainConnectString, key.ToLower(), certtype);
                if (item == null)
                {
                    WechatAccessToken appAccessToken = WeChatUrlBLL.GetAppToken(AppId(certtype), AppSecret(certtype));
                    item = new WeChatConfigModel();
                    item.ParamKey = key;
                    item.ParamValue = appAccessToken.access_token;
                    item.ExpirationTime = DateTime.Now.AddSeconds(appAccessToken.expires_in);
                    WeChatConfigBLL.Add(BSFConfig.MainConnectString, item);
                    //return item.ParamValue;
                    return item;
                }
                //提前10分钟刷新access_token
                else if (item.ExpirationTime <= DateTime.Now.AddMinutes(-10))
                {
                    WechatAccessToken appAccessToken = WeChatUrlBLL.GetAppToken(AppId(certtype), AppSecret(certtype));
                    //更新access_token
                    item.ParamValue = appAccessToken.access_token;
                    item.ExpirationTime = DateTime.Now.AddSeconds(appAccessToken.expires_in);
                    WeChatConfigBLL.Update(BSFConfig.MainConnectString, item);
                    //return item.ParamValue;
                    return item;
                }
                else
                {
                    //return item.ParamValue;
                    return item;
                }
            }
        }

        /// <summary>
        /// 获取jsapi_ticket
        /// </summary>
        /// <returns></returns>
        public static WeChatConfigModel BaseJsApiTicket(WeixinType certtype)
        {
            if (IsDebug)
            {
                WeChatConfigModel item = new WeChatConfigModel()
                {
                    ParamKey = "jsapi_ticket",
                    ParamValue = DevConfig.JSApiTicket,
                    ExpirationTime = DateTime.Now.AddDays(30)
                };
                return item;
            }
            else
            {
                string key = "jsapi_ticket";
                WeChatConfigModel info = WeChatConfigBLL.GetModelByParamKey(BSFConfig.MainConnectString, key.ToLower(), certtype);
                if (info == null)
                {
                    string accesstoken = BaseAccessToken(certtype).ParamValue;
                    WechatTicket item = WeChatUrlBLL.GetAppJsTicket(accesstoken);
                    if (item.errcode.Equals(0))
                    {
                        string JSApi_Ticket = item.ticket;
                        info = new WeChatConfigModel();
                        info.ParamKey = key;
                        info.ParamValue = JSApi_Ticket;
                        info.WechatType = (int)certtype;
                        info.ExpirationTime = DateTime.Now.AddSeconds(item.expires_in);
                        WeChatConfigBLL.Add(BSFConfig.MainConnectString, info);
                        //return info.ParamValue;
                        return info;
                    }
                    //return string.Empty;
                    return null;
                }
                //提前10分钟刷新access_token
                else if (info.ExpirationTime <= DateTime.Now.AddMinutes(-10))
                {
                    string accesstoken = BaseAccessToken(certtype).ParamValue;
                    WechatTicket item = WeChatUrlBLL.GetAppJsTicket(accesstoken);
                    if (item.errcode.Equals(0))
                    {
                        info.ParamValue = item.ticket;
                        info.ExpirationTime = DateTime.Now.AddSeconds(item.expires_in);
                        WeChatConfigBLL.Update(BSFConfig.MainConnectString, info);
                        //return info.ParamValue;
                        return info;
                    }
                    //return string.Empty;
                    return null;
                }
                else
                {
                    //return info.ParamValue;
                    return info;
                }
            }
        }

        #endregion


    }
}
